package thread;

import java.util.Objects;

public class Demo16 {
    private static int count = 0;
    private static int count2 = 0;

    public static void main(String[] args) throws InterruptedException {
        //创建 2个线程，针对同一个变量进行循环自增

        //定义一个锁对象
        //可以是任意的对象
        Object locker = new Object();
        Object locker2 = new Object();

        Thread t1 = new Thread(() -> {
            //int myCount = 0;
            for (int i = 0; i < 50000; i++) {
                //myCount++;
                synchronized (locker) {
                    count++;
                }
            }
        });

        Thread t2 = new Thread(() -> {
            //int myCount = 0;
            for (int i = 0; i < 50000; i++) {
                //myCount++;
                synchronized (locker) {
                    count++;
                }
            }
        });

        t1.start();
        t2.start();
        t1.join();
        t2.join();

        //此处得到的预期结果为 10w
        System.out.println("count = " + count);
    }
}
